import random
from datetime import datetime

# 初始化用户账户余额
user_money = 1000.00

# 商品列表（每个商品是包含名称、价格和数量的列表）
goods = [
    ["苹果", 8.5, 3],
    ["香蕉", 4.5, 3],
    ["牛奶", 12.0, 3],
    ["面包", 7.0, 3],
    ["鸡蛋", 1.5, 3],
    ["牛肉", 38.0, 3],
    ["空调", 500.0, 3]
]

# 优惠券池（商品名称: 折扣率）
coupons_pool = {
    "空调": 0.8,  # 8折
    "苹果": 0.9,  # 9折
    "香蕉": 0.85,  # 85折
    "牛奶": 0.75,  # 75折
    "面包": 0.95,  # 95折
    "鸡蛋": 0.88,  # 88折
    "牛肉": 0.7,  # 7折
    "无": 1.0  # 无折扣
}

# 初始化购物车（空列表）
shopping_cart = []

# 购物开始时间
start_time = datetime.now()

print("===== 欢迎来到超市购物系统 =====")
print(f"您的账户余额: ￥{user_money:.2f}")

# 1. 抽取优惠券
print("\n===== 优惠券抽取 =====")
# 随机选择一张优惠券
coupon_item = random.choice(list(coupons_pool.keys()))
discount_rate = coupons_pool[coupon_item]

if coupon_item == "无":
    print("很遗憾，您抽到了一张无优惠券")
else:
    print(f"恭喜！您抽到一张【{coupon_item}】{int(discount_rate * 10)}折优惠券！")
print("======================")

print("提示：")
print("  - 输入商品编号购物")
print("  - 输入'T'退货")
print("  - 输入'Q'结算退出")

# 主购物循环
while True:
    # 显示商品列表
    print("\n====== 商品清单 ======")
    for i in range(len(goods)):
        # 检查是否有优惠券
        discount_note = ""
        if goods[i][0] == coupon_item and discount_rate < 1.0:
            discount_note = f" (优惠价: ￥{goods[i][1] * discount_rate:.2f})"
        print(f"{i + 1}. {goods[i][0]:5} ￥{goods[i][1]:.2f} \t{goods[i][2]}件{discount_note}")
    print("======================")

    # 显示购物车
    if shopping_cart:
        print("\n====== 当前购物车 ======")
        for idx, item in enumerate(shopping_cart, 1):
            print(f"{idx}. {item[0]} x {item[2]} = ￥{item[1] * item[2]:.2f}")
        print("========================")

    # 获取用户输入
    choice = input("\n请输入操作 (商品编号/T退货/Q结算): ").strip().upper()

    # 退出条件
    if choice == 'Q':
        break

    # 退货功能
    if choice == 'T':
        if not shopping_cart:
            print("购物车为空，无法退货！")
            continue

        # 显示购物车
        print("\n====== 购物车商品 ======")
        for idx, item in enumerate(shopping_cart, 1):
            print(f"{idx}. {item[0]} x {item[2]} = ￥{item[1] * item[2]:.2f}")

        # 获取退货商品编号
        return_idx = input("请输入要退货的商品编号 (输入C取消): ").strip()
        if return_idx.upper() == 'C':
            continue

        if return_idx.isdigit():
            return_idx = int(return_idx) - 1
            if 0 <= return_idx < len(shopping_cart):
                item_to_return = shopping_cart[return_idx]

                # 恢复库存
                for i in range(len(goods)):
                    if goods[i][0] == item_to_return[0]:
                        goods[i][2] += item_to_return[2]
                        break

                # 退款
                user_money += item_to_return[1] * item_to_return[2]

                # 从购物车移除
                return_item = shopping_cart.pop(return_idx)

                print(f"✅ 退货成功！已退还 {return_item[0]} x {return_item[2]}")
                print(f"退款金额: ￥{return_item[1] * return_item[2]:.2f}")
                print(f"当前余额: ￥{user_money:.2f}")
            else:
                print("⚠ 无效的退货商品编号！")
        else:
            print("⚠ 无效输入！请输入商品编号或C取消")
        continue

    # 检查输入是否有效
    if choice.isdigit():
        choice_idx = int(choice) - 1
        # 检查商品是否存在
        if 0 <= choice_idx < len(goods):
            # 获取商品信息
            item_name = goods[choice_idx][0]
            original_price = goods[choice_idx][1]
            stock = goods[choice_idx][2]

            # 应用优惠券
            if item_name == coupon_item and discount_rate < 1.0:
                price = original_price * discount_rate
                discount_note = f" (优惠价: ￥{price:.2f})"
            else:
                price = original_price
                discount_note = ""

            # 检查库存
            if stock <= 0:
                print(f"❌ 商品已售光！")
                continue

            # 获取购买数量
            while True:
                quantity_input = input(f"请输入购买数量 (库存: {stock}件{discount_note}): ").strip()
                if not quantity_input:
                    quantity = 1
                    break
                elif quantity_input.isdigit():
                    quantity = int(quantity_input)
                    if 1 <= quantity <= stock:
                        break
                    else:
                        print(f"⚠ 数量无效！请输入1-{stock}之间的数字")
                else:
                    print("⚠ 无效输入！请输入数字")

            # 计算总价
            total_price = price * quantity

            # 检查余额是否足够
            if user_money >= total_price:
                # 添加到购物车
                # 检查购物车是否已有该商品
                found = False
                for item in shopping_cart:
                    if item[0] == item_name and item[1] == price:
                        item[2] += quantity
                        found = True
                        break

                if not found:
                    shopping_cart.append([item_name, price, quantity])

                # 扣款
                user_money -= total_price

                # 减少库存
                goods[choice_idx][2] -= quantity

                print(f"✅ 购买成功！添加 {item_name} x {quantity} 到购物车")
                if discount_note:
                    print(f"  优惠券生效: 原价￥{original_price:.2f} → 优惠价￥{price:.2f}")
                print(f"当前余额: ￥{user_money:.2f}")
            else:
                # 余额不足处理
                print(f"❌ 余额不足！{item_name} x {quantity} 需要 ￥{total_price:.2f}")
        else:
            print("⚠ 无效编号！请选择1-{}之间的数字".format(len(goods)))
    else:
        print("⚠ 无效输入！请输入商品编号、T退货或Q退出")

# 计算购物时间
end_time = datetime.now()
shopping_duration = end_time - start_time
shopping_minutes = shopping_duration.total_seconds() // 60
shopping_seconds = shopping_duration.total_seconds() % 60

# 打印购物小票
print("\n" + "=" * 50)
print(" " * 15 + "购物小票")
print("=" * 50)
print(f"购物时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"结算时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"购物时长: {int(shopping_minutes)}分{int(shopping_seconds)}秒")
print("-" * 50)

if not shopping_cart:
    print("购物车为空，未购买任何商品！")
else:
    total_items = 0
    total_value = 0.0
    original_total = 0.0  # 原价总计

    print("商品名称      单价    数量     小计")
    print("-" * 50)
    for item in shopping_cart:
        item_total = item[1] * item[2]
        total_items += item[2]
        total_value += item_total

        # 如果是优惠商品，显示原价
        if item[1] != next((g[1] for g in goods if g[0] == item[0]), item[1]):
            original_price = next(g[1] for g in goods if g[0] == item[0])
            original_total += original_price * item[2]
            print(f"{item[0]:6}  ￥{item[1]:>7.2f}  x{item[2]:<3}  ￥{item_total:>7.2f} (原价:￥{original_price:.2f})")
        else:
            original_total += item_total
            print(f"{item[0]:6}  ￥{item[1]:>7.2f}  x{item[2]:<3}  ￥{item_total:>7.2f}")

    print("-" * 50)

    # 显示优惠信息
    if coupon_item != "无" and discount_rate < 1.0:
        discount_saving = original_total - total_value
        print(f"优惠券: 【{coupon_item}】{int(discount_rate * 10)}折")
        print(f"优惠节省: ￥{discount_saving:.2f}")

    print(f"商品总数: {total_items}件")
    print(f"商品总价: ￥{original_total:.2f}")
    print(f"实际支付: ￥{total_value:.2f}")
    print(f"账户余额: ￥{user_money:.2f}")

print("=" * 50)
print("感谢您的光临！欢迎下次再来！")
print("=" * 50)